package com.ruoyi.network.utils;

import cn.hutool.core.collection.CollUtil;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.network.domain.entity.IpAddress;
import com.ruoyi.network.domain.entity.IpRange;
import com.ruoyi.network.enums.ExpiryStatusEnum;
import com.ruoyi.network.enums.UasgeStatusEnum;
import com.ruoyi.network.model.vo.IpAddressImportExcelVO;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * IP地址表格工具类抽取
 *
 * @author Administrator
 */
@Component
public class IpAddressExcelUtil {
    @Resource
    private ISysDeptService deptService;

    private static IpAddressExcelUtil instance;

    @Autowired
    public void setInstance(IpAddressExcelUtil instance) {
        IpAddressExcelUtil.instance = instance;
    }

    /**
     * 解析数据结构转换
     *
     * @param vos          待转换数据集
     * @param rangeNames   网段名称映射结构
     * @param ipAddressMap 已存在的IP地址
     * @return List<IpAddress> 转换结果
     */
    public static List<IpAddress> convertIpAddressExcelVO(List<IpAddressImportExcelVO> vos, Map<String, IpRange> rangeNames, Map<Long, IpAddress> ipAddressMap) {
        if (CollUtil.isEmpty(vos)) {
            return Collections.emptyList();
        }
        List<IpAddress> list = new ArrayList<>(vos.size());
        for (IpAddressImportExcelVO v : vos) {
            IpRange ipRange = rangeNames.get(v.getRangeKey());
            if (ipRange == null) {
                throw new ServiceException("IP网段不存在" + v.getRangeName());
            }

            if (ipAddressMap.getOrDefault(v.getIpValue(), null) != null) {
                throw new ServiceException("IP地址已存在:" + v.getIpFormatValue());
            }

            if (v.getIpValue() < ipRange.getStartIp() || v.getIpValue() > ipRange.getEndIp()) {
                throw new ServiceException("IP地址不在指定网段内:" + v.getIpFormatValue());
            }

            IpAddress ipAddress = new IpAddress();
            ipAddress.setIpValue(v.getIpValue());
            ipAddress.setHostname(v.getHostname());
            ipAddress.setRangeId(ipRange.getId());
            ipAddress.setUsageStatus(UasgeStatusEnum.UNUSED);
            ipAddress.setUsageBizId(null);
            ipAddress.setUsageUserId(null);
            ipAddress.setMacAddress(v.getMacAddress());
            ipAddress.setExpiryStatus(ExpiryStatusEnum.INTERIM);
            list.add(ipAddress);
        }
        return list;
    }
}
